<template>
  <div class="space-y-4 lg:space-y-6">
    <!-- 页面标题和操作栏 -->
    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
      <div>
        <h1 class="text-xl sm:text-2xl font-bold text-gray-900">员工管理</h1>
        <p class="text-gray-600 mt-1 text-sm sm:text-base">管理酒店员工信息，包括新增、编辑、删除等操作</p>
      </div>
      <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3">
        <button
          class="btn-secondary text-sm sm:text-base"
          @click="exportEmployees"
          :disabled="loading"
        >
          <span class="mr-2">📤</span>
          导出数据
        </button>
        <router-link to="/employees/add" class="btn-primary text-sm sm:text-base">
          <span class="mr-2">➕</span>
          新增员工
        </router-link>
      </div>
    </div>

    <!-- 搜索和筛选栏 -->
    <div class="card">
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6 2xl:grid-cols-8 gap-4 xl:gap-6">
        <div>
          <label class="form-label">姓名</label>
          <input 
            v-model="searchForm.name" 
            type="text" 
            class="form-input" 
            placeholder="请输入员工姓名"
            @input="debouncedSearch"
          />
        </div>
        <div>
          <label class="form-label">性别</label>
          <select v-model="searchForm.gender" class="form-input" @change="handleSearch">
            <option value="">全部</option>
            <option value="MALE">男</option>
            <option value="FEMALE">女</option>
          </select>
        </div>
        <div>
          <label class="form-label">职位</label>
          <input 
            v-model="searchForm.position" 
            type="text" 
            class="form-input" 
            placeholder="请输入职位"
            @input="debouncedSearch"
          />
        </div>
        <div>
          <label class="form-label">状态</label>
          <select v-model="searchForm.status" class="form-input" @change="handleSearch">
            <option value="">全部</option>
            <option value="ACTIVE">在职</option>
            <option value="INACTIVE">离职</option>
          </select>
        </div>
      </div>
      <div class="flex items-center justify-between mt-4 pt-4 border-t border-warm-200">
        <div class="flex items-center space-x-4">
          <button class="btn-secondary" @click="resetSearch">
            <span class="mr-2">🔄</span>
            重置
          </button>
          <button class="btn-primary" @click="handleSearch">
            <span class="mr-2">🔍</span>
            搜索
          </button>
        </div>
        <div class="text-sm text-gray-600">
          共找到 {{ pagination.totalElements }} 条记录
        </div>
      </div>
    </div>

    <!-- 批量操作栏 -->
    <div v-if="selectedEmployees.length > 0" class="card bg-blue-50 border-blue-200">
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-4">
          <span class="text-sm font-medium text-blue-800">
            已选择 {{ selectedEmployees.length }} 个员工
          </span>
          <button 
            class="text-sm text-blue-600 hover:text-blue-800"
            @click="selectAll"
          >
            全选
          </button>
          <button 
            class="text-sm text-blue-600 hover:text-blue-800"
            @click="clearSelection"
          >
            清空
          </button>
        </div>
        <div class="flex items-center space-x-2">
          <button 
            class="btn-danger"
            @click="batchDelete"
            :disabled="loading"
          >
            <span class="mr-2">🗑️</span>
            批量删除
          </button>
        </div>
      </div>
    </div>

    <!-- 员工列表 -->
    <div class="card">
      <!-- 移动端卡片视图 -->
      <div class="block lg:hidden space-y-4">
        <div v-if="loading" class="text-center py-8">
          <div class="flex items-center justify-center space-x-2">
            <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary-600"></div>
            <span class="text-gray-600">加载中...</span>
          </div>
        </div>
        <div v-else-if="employees.length === 0" class="text-center py-8 text-gray-500">
          暂无员工数据
        </div>
        <div v-else v-for="employee in employees" :key="employee.id"
             class="bg-white border border-warm-200 rounded-lg p-4 space-y-3">
          <div class="flex items-center justify-between">
            <div class="flex items-center space-x-3">
              <input
                type="checkbox"
                :value="employee.id"
                v-model="selectedEmployees"
                class="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
              />
              <div class="w-10 h-10 bg-gradient-to-br from-primary-400 to-primary-600 rounded-full flex items-center justify-center">
                <span class="text-white font-medium text-sm">{{ employee.name.charAt(0) }}</span>
              </div>
              <div>
                <div class="font-medium text-gray-900">{{ employee.name }}</div>
                <div class="text-sm text-gray-500">
                  {{ FormatUtils.getGenderIcon(employee.gender) }}
                  {{ FormatUtils.formatGender(employee.gender) }} · {{ employee.age }}岁
                </div>
              </div>
            </div>
            <span :class="[
              'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
              employee.status === 'ACTIVE'
                ? 'bg-green-100 text-green-800'
                : 'bg-red-100 text-red-800'
            ]">
              {{ FormatUtils.formatStatus(employee.status) }}
            </span>
          </div>
          <div class="grid grid-cols-2 gap-3 text-sm">
            <div>
              <span class="text-gray-500">联系方式:</span>
              <div class="mt-1">
                <div>📱 {{ FormatUtils.formatPhone(employee.phone) }}</div>
                <div class="text-gray-600">📧 {{ employee.email }}</div>
              </div>
            </div>
            <div>
              <span class="text-gray-500">职位信息:</span>
              <div class="mt-1">
                <div class="font-medium">{{ employee.position }}</div>
                <div class="text-gray-500">角色ID: {{ employee.roleId }}</div>
              </div>
            </div>
          </div>
          <div class="flex items-center justify-between pt-2 border-t border-gray-100">
            <div class="text-xs text-gray-500">
              入职: {{ FormatUtils.formatDate(employee.hireDate) }}
            </div>
            <div class="flex items-center space-x-3">
              <router-link
                :to="`/employees/edit/${employee.id}`"
                class="text-primary-600 hover:text-primary-800 text-sm font-medium"
              >
                编辑
              </router-link>
              <button
                @click="deleteEmployee(employee)"
                class="text-red-600 hover:text-red-800 text-sm font-medium"
                :disabled="loading"
              >
                删除
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 桌面端表格视图 -->
      <div class="hidden lg:block overflow-x-auto -mx-4 sm:-mx-5 lg:-mx-6 xl:-mx-6 2xl:-mx-8">
        <div class="px-4 sm:px-5 lg:px-6 xl:px-6 2xl:px-8">
          <table class="table">
            <thead class="table-header">
              <tr>
                <th class="table-header-cell">
                  <input
                    type="checkbox"
                    :checked="isAllSelected"
                    @change="toggleSelectAll"
                    class="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                  />
                </th>
                <th class="table-header-cell">员工信息</th>
                <th class="table-header-cell xl:table-cell hidden">性别</th>
                <th class="table-header-cell xl:table-cell hidden">年龄</th>
                <th class="table-header-cell">联系方式</th>
                <th class="table-header-cell">职位信息</th>
                <th class="table-header-cell 2xl:table-cell hidden">角色ID</th>
                <th class="table-header-cell">状态</th>
                <th class="table-header-cell">入职时间</th>
                <th class="table-header-cell">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="loading" class="table-row">
                <td colspan="9" class="table-cell text-center py-8">
                  <div class="flex items-center justify-center space-x-2">
                    <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary-600"></div>
                    <span class="text-gray-600">加载中...</span>
                  </div>
                </td>
              </tr>
              <tr v-else-if="employees.length === 0" class="table-row">
                <td colspan="9" class="table-cell text-center py-8 text-gray-500">
                  暂无员工数据
                </td>
              </tr>
              <tr
                v-else
                v-for="employee in employees"
                :key="employee.id"
                class="table-row"
              >
                <td class="table-cell">
                  <input
                    type="checkbox"
                    :value="employee.id"
                    v-model="selectedEmployees"
                    class="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                  />
                </td>
                <td class="table-cell">
                  <div class="flex items-center space-x-3">
                    <div class="w-8 h-8 xl:w-10 xl:h-10 bg-gradient-to-br from-primary-400 to-primary-600 rounded-full flex items-center justify-center">
                      <span class="text-white font-medium text-sm xl:text-base">{{ employee.name.charAt(0) }}</span>
                    </div>
                    <div>
                      <div class="font-medium text-gray-900">{{ employee.name }}</div>
                      <div class="text-sm text-gray-500 xl:hidden">
                        {{ FormatUtils.getGenderIcon(employee.gender) }}
                        {{ FormatUtils.formatGender(employee.gender) }} · {{ employee.age }}岁
                      </div>
                    </div>
                  </div>
                </td>
              <!-- 性别列 (XL屏幕显示) -->
              <td class="table-cell xl:table-cell hidden">
                <div class="flex items-center space-x-1">
                  <span>{{ FormatUtils.getGenderIcon(employee.gender) }}</span>
                  <span class="text-sm">{{ FormatUtils.formatGender(employee.gender) }}</span>
                </div>
              </td>
              <!-- 年龄列 (XL屏幕显示) -->
              <td class="table-cell xl:table-cell hidden">
                <span class="text-sm font-medium">{{ employee.age }}岁</span>
              </td>
              <td class="table-cell">
                <div class="space-y-1">
                  <div class="text-sm">📱 {{ FormatUtils.formatPhone(employee.phone) }}</div>
                  <div class="text-sm text-gray-600">📧 {{ employee.email }}</div>
                </div>
              </td>
              <td class="table-cell">
                <div class="font-medium">{{ employee.position }}</div>
                <div class="text-sm text-gray-500 2xl:hidden">角色ID: {{ employee.roleId }}</div>
              </td>
              <!-- 角色ID列 (2XL屏幕显示) -->
              <td class="table-cell 2xl:table-cell hidden">
                <span class="text-sm font-mono bg-gray-100 px-2 py-1 rounded">{{ employee.roleId }}</span>
              </td>
              <td class="table-cell">
                <span :class="[
                  'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
                  employee.status === 'ACTIVE' 
                    ? 'bg-green-100 text-green-800' 
                    : 'bg-red-100 text-red-800'
                ]">
                  {{ FormatUtils.formatStatus(employee.status) }}
                </span>
              </td>
              <td class="table-cell">
                <div class="text-sm">{{ FormatUtils.formatDate(employee.hireDate) }}</div>
                <div class="text-xs text-gray-500">
                  {{ FormatUtils.formatDate(employee.createdTime, 'YYYY-MM-DD HH:mm') }}
                </div>
              </td>
              <td class="table-cell">
                <div class="flex items-center space-x-2">
                  <router-link 
                    :to="`/employees/edit/${employee.id}`"
                    class="text-primary-600 hover:text-primary-800 text-sm font-medium"
                  >
                    编辑
                  </router-link>
                  <button 
                    @click="deleteEmployee(employee)"
                    class="text-red-600 hover:text-red-800 text-sm font-medium"
                    :disabled="loading"
                  >
                    删除
                  </button>
                </div>
              </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="pagination.totalPages > 1" class="flex items-center justify-between mt-6 pt-6 border-t border-warm-200">
        <div class="text-sm text-gray-600">
          显示第 {{ (pagination.number) * pagination.size + 1 }} - 
          {{ Math.min((pagination.number + 1) * pagination.size, pagination.totalElements) }} 条，
          共 {{ pagination.totalElements }} 条记录
        </div>
        <div class="flex items-center space-x-2">
          <button 
            @click="changePage(pagination.number - 1)"
            :disabled="pagination.first || loading"
            class="px-3 py-1 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            上一页
          </button>
          <div class="flex items-center space-x-1">
            <button 
              v-for="page in visiblePages" 
              :key="page"
              @click="changePage(page - 1)"
              :class="[
                'px-3 py-1 text-sm border rounded-md',
                page === pagination.number + 1
                  ? 'bg-primary-600 text-white border-primary-600'
                  : 'border-gray-300 hover:bg-gray-50'
              ]"
            >
              {{ page }}
            </button>
          </div>
          <button 
            @click="changePage(pagination.number + 1)"
            :disabled="pagination.last || loading"
            class="px-3 py-1 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { EmployeeService, type Employee, type EmployeeQuery, type PageResponse } from '@/api/employee'
import { ApiWrapper, MessageUtils, FormatUtils } from '@/api/utils'

// 响应式数据
const loading = ref(false)
const employees = ref<Employee[]>([])
const selectedEmployees = ref<number[]>([])

// 搜索表单
const searchForm = reactive<EmployeeQuery>({
  name: '',
  gender: undefined,
  position: '',
  status: undefined,
  page: 0,
  size: 10
})

// 分页信息
const pagination = ref<PageResponse<Employee>>({
  content: [],
  totalElements: 0,
  totalPages: 0,
  size: 10,
  number: 0,
  first: true,
  last: true,
  empty: true
})

// 计算属性
const isAllSelected = computed(() => {
  return employees.value.length > 0 && selectedEmployees.value.length === employees.value.length
})

const visiblePages = computed(() => {
  const current = pagination.value.number + 1
  const total = pagination.value.totalPages
  const delta = 2
  const range = []
  const rangeWithDots = []

  for (let i = Math.max(2, current - delta); i <= Math.min(total - 1, current + delta); i++) {
    range.push(i)
  }

  if (current - delta > 2) {
    rangeWithDots.push(1, '...')
  } else {
    rangeWithDots.push(1)
  }

  rangeWithDots.push(...range)

  if (current + delta < total - 1) {
    rangeWithDots.push('...', total)
  } else if (total > 1) {
    rangeWithDots.push(total)
  }

  return rangeWithDots.filter(page => page !== '...' && typeof page === 'number')
})

// 防抖搜索
let searchTimeout: NodeJS.Timeout
const debouncedSearch = () => {
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    handleSearch()
  }, 500)
}

// 加载员工列表
const loadEmployees = async () => {
  loading.value = true
  try {
    const response = await EmployeeService.getEmployees(searchForm)
    employees.value = response.content
    pagination.value = response
  } catch (error) {
    MessageUtils.error('加载员工列表失败')
    console.error('Load employees error:', error)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  searchForm.page = 0
  selectedEmployees.value = []
  loadEmployees()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    name: '',
    gender: undefined,
    position: '',
    status: undefined,
    page: 0,
    size: 10
  })
  selectedEmployees.value = []
  loadEmployees()
}

// 切换页面
const changePage = (page: number) => {
  if (page >= 0 && page < pagination.value.totalPages) {
    searchForm.page = page
    selectedEmployees.value = []
    loadEmployees()
  }
}

// 选择相关
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedEmployees.value = []
  } else {
    selectedEmployees.value = employees.value.map(emp => emp.id!).filter(id => id !== undefined)
  }
}

const selectAll = () => {
  selectedEmployees.value = employees.value.map(emp => emp.id!).filter(id => id !== undefined)
}

const clearSelection = () => {
  selectedEmployees.value = []
}

// 删除员工
const deleteEmployee = async (employee: Employee) => {
  const result = await ApiWrapper.deleteWithConfirm(
    () => EmployeeService.deleteEmployee(employee.id!),
    {
      confirmMessage: `确定要删除员工"${employee.name}"吗？此操作不可恢复。`,
      successMessage: '员工删除成功'
    }
  )
  
  if (result !== null) {
    await loadEmployees()
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedEmployees.value.length === 0) {
    MessageUtils.warning('请先选择要删除的员工')
    return
  }

  const result = await ApiWrapper.batchDeleteWithConfirm(
    () => EmployeeService.batchDeleteEmployees({ ids: selectedEmployees.value }),
    selectedEmployees.value.length
  )
  
  if (result !== null) {
    selectedEmployees.value = []
    await loadEmployees()
  }
}

// 导出员工数据
const exportEmployees = async () => {
  await ApiWrapper.request(
    async () => {
      const blob = await EmployeeService.exportEmployees(searchForm)
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `员工数据_${FormatUtils.formatDate(new Date(), 'YYYY-MM-DD')}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    },
    {
      loadingText: '导出中...',
      successMessage: '数据导出成功'
    }
  )
}

// 组件挂载时加载数据
onMounted(() => {
  loadEmployees()
})
</script>
